package com.zenchn.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zenchn.annotation.OperLog;
import com.zenchn.entity.HttpDataResult;
import com.zenchn.enums.DataValueStyleEnum;
import com.zenchn.enums.OperLogActionEnum;
import com.zenchn.exception.CheckException;
import com.zenchn.model.TSysConfig;
import com.zenchn.model.TSysConfigExample;
import com.zenchn.service.ConfigService;
import com.zenchn.utils.CommonUtils;
import io.swagger.annotations.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * 基础参数模块控制器
 *
 * @author dingxinfa
 * @date 2020-04-20
 **/

@RestController
@RequestMapping(value = "baseConfig")
@Api(value = "基础参数模块相关接口",tags="系统管理-基础参数")
@RequiresPermissions("base:config")
public class BaseConfigController {

    private final String MODULE="系统管理>基础参数";


    @Resource
    private ConfigService configService;


    /**
     * 分页获取基础参数列表
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module=MODULE,action= OperLogActionEnum.QUERY,detail="分页获取基础参数列表")
    @ApiOperation(value = "分页获取基础参数列表", notes = "分页获取基础参数列表")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "keyword", value = "参数名称，参数编码"),
            @ApiImplicitParam(dataType = "Integer", name = "page", value = "当前第page页"),
            @ApiImplicitParam(dataType = "Integer", name = "pageSize", value = "每页pageSize数量")
    })
    @GetMapping(value = "/list")
    @RequiresPermissions("base:config")
    public ResponseEntity<HttpDataResult<PageInfo<TSysConfig>>> list(
            @RequestParam(required = false, value = "keyword") String keyword,
            @RequestParam(required = false, value = "page", defaultValue = "1") Integer page,
            @RequestParam(required = false, value = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest request, HttpServletResponse response) throws Exception{
        HttpDataResult<PageInfo<TSysConfig>> result = new HttpDataResult<>(request.getRequestURI());

        TSysConfigExample configExample=new TSysConfigExample();
        if (null!=keyword && !"".equals(keyword.trim())){
            configExample.createCriteria().andConfigCodeLike("%"+keyword.trim()+"%");

            TSysConfigExample.Criteria criteria2=configExample.createCriteria();
            criteria2.andConfigNameLike("%"+keyword.trim()+"%");
            configExample.or(criteria2);

            TSysConfigExample.Criteria criteria3=configExample.createCriteria();
            criteria3.andConfigValueLike("%"+keyword.trim()+"%");
            configExample.or(criteria3);
        }
        configExample.setOrderByClause("create_time desc");

        PageHelper.startPage(page,pageSize);
        PageInfo<TSysConfig> pageInfo = new PageInfo<TSysConfig>(configService.selectByExample(configExample));

        result.setData(pageInfo);

        result.setMessage("获取参数列表成功.");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 获取 参数值类型 列表
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module=MODULE,action= OperLogActionEnum.QUERY,detail="获取参数值类型列表",isSaveRequestData=false)
    @ApiOperation(value = "参数值类型列表", notes = "参数值类型列表")
    @GetMapping(value = "/valueStyleList")
    public ResponseEntity<HttpDataResult<List<String>>> valueStyleList(HttpServletRequest request, HttpServletResponse response) throws Exception{
        HttpDataResult<List<String>> result = new HttpDataResult<>(request.getRequestURI());

        result.setData(DataValueStyleEnum.getValueList());

        result.setMessage("获取权限列表成功.");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }


    /**
     * 新增参数保存提交
     * @param config
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module=MODULE,action= OperLogActionEnum.INSERT,detail="新增参数保存提交")
    @ApiOperation(value = "新增参数保存提交", notes = "新增参数保存提交")
    @ApiParam( type = "TSysConfig",name = "config", value = "系统参数对象", required = true)
    @PostMapping(value = "/addSubmit")
    @RequiresPermissions("base:config:add")
    public ResponseEntity<HttpDataResult<String>> addSubmit(
            @RequestBody @Valid TSysConfig config, BindingResult results,
            HttpServletRequest request, HttpServletResponse response) throws Exception{

        if (results.hasErrors()){
            throw new CheckException(Objects.requireNonNull(results.getFieldError()).getDefaultMessage());
        }

        if (!configService.verifyConfigCode(config.getConfigId(),config.getConfigCode())){
            throw new CheckException("参数编码重复，无法新增提交！");
        }

        HttpDataResult<String> result = new HttpDataResult<>(request.getRequestURI());

        config.setCreateTime(LocalDateTime.now());
        config.setConfigId(CommonUtils.randomUUID());
        config.setIsMust(true);
        configService.insert(config);

        result.setData(config.getConfigId());

        result.setMessage("新增参数成功。");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);

    }


    /***
     * 获取参数信息详情
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module=MODULE,action= OperLogActionEnum.QUERY,detail="获取参数信息详情")
    @ApiOperation(value = "获取参数信息详情", notes = "获取参数信息详情")
    @ApiImplicitParam(dataType = "String", name = "configId", value = "参数ID", required = true)
    @GetMapping(value = "/getConfigInfo")
    public ResponseEntity<HttpDataResult<TSysConfig>> getConfigInfo(
            @RequestParam(value = "configId") String configId,
            HttpServletRequest request, HttpServletResponse response) throws Exception{
        HttpDataResult<TSysConfig> result = new HttpDataResult<>(request.getRequestURI());

        TSysConfig config=configService.selectByPrimaryKey(configId);

        result.setData(config);
        result.setMessage("OK");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 修改参数保存提交
     * @param config
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module=MODULE,action= OperLogActionEnum.UPDATE,detail="修改参数保存提交",isSaveRequestData=true)
    @ApiOperation(value = "修改参数保存提交", notes = "修改参数保存提交")
    @ApiParam( type = "TSysConfig", name = "config", value = "系统参数对象", required = true)
    @PutMapping(value = "/modifySubmit")
    @RequiresPermissions("base:config:modify")
    public ResponseEntity<HttpDataResult<String>> modifySubmit(
            @RequestBody @Valid TSysConfig config, BindingResult results,
            HttpServletRequest request, HttpServletResponse response) throws Exception {

        if (results.hasErrors()){
            throw new CheckException(Objects.requireNonNull(results.getFieldError()).getDefaultMessage());
        }

        if (!configService.verifyConfigCode(config.getConfigId(),config.getConfigCode())){
            throw new CheckException("参数编码重复，无法修改保存！");
        }


        HttpDataResult<String> result = new HttpDataResult<>(request.getRequestURI());

        configService.updateByPrimaryKeySelective(config);

        result.setData(config.getConfigId());

        result.setMessage("修改参数成功。");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }


    /***
     * 验证   参数编码  唯一性
     * @param configId
     * @param configCode
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @OperLog(module=MODULE,action= OperLogActionEnum.CHECK,detail="验证参数编码唯一性",isSaveRequestData=true)
    @ApiOperation(value = "验证参数编码唯一性", notes = "验证参数编码唯一性")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "configId", value = "参数ID", required = false),
            @ApiImplicitParam(dataType = "String", name = "configCode", value = "参数编码", required = true)
    })
    @GetMapping(value = "/verifyConfigCode")
    public ResponseEntity<HttpDataResult<Boolean>> verifyConfigCode(
            @RequestParam(required = false, value = "configId") String configId,
            @RequestParam( value = "configCode") String configCode,
            HttpServletRequest request, HttpServletResponse response) throws Exception{
        HttpDataResult<Boolean> result = new HttpDataResult<>(request.getRequestURI());


            result.setData(configService.verifyConfigCode(configId,configCode));


        result.setMessage("验证参数编码唯一性成功.");
        result.setStatus(HttpStatus.OK.value());
        return new ResponseEntity<>(result, HttpStatus.OK);

    }
}
